<?php
//by willson 105328468@qq.com 2014/10/11
//index page interface

class goods extends core {
	private $goods_mod;

	public function __construct() {
		parent::__construct();
		$this->goods_mod = m("goods");
	}

	//商品列表
	public function index() {
		$where = "";
		$offset = (isset($_GET['offset']) && intval($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && intval($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		//分类
		$category_id = (isset($_GET['category_id']) && intval($_GET['category_id'])) ? intval($_GET['category_id']) : 0;
		//扩展属性
		$ext_property = (isset($_GET['ext_property']) && trim($_GET['ext_property'])) ? trim($_GET['ext_property']) : '';
		//产地
		$country_id = (isset($_GET['country_id']) && intval($_GET['country_id'])) ? intval($_GET['country_id']) : 0;
		//品牌
		$brand_id = (isset($_GET['brand_id']) && intval($_GET['brand_id'])) ? intval($_GET['brand_id']) : 0;
		//店铺id
		$shop_id = (isset($_GET['shop_id']) && intval($_GET['shop_id'])) ? intval($_GET['shop_id']) : 0;
		//价格区间
		$min_price = (isset($_GET['min_price']) && intval($_GET['min_price'])) ? intval($_GET['min_price']) : 0;
		$max_price = (isset($_GET['max_price']) && intval($_GET['max_price'])) ? intval($_GET['max_price']) : 0;
		//关键词搜索
		$keyword = (isset($_GET['keyword']) && trim($_GET['keyword'])) ? trim(urldecode($_GET['keyword'])) : '';
		//排序字段
		$order_field = (isset($_GET['order_field']) && trim($_GET['order_field'])) ? trim($_GET['order_field']) : '';
		//排序方向
		$order_sort = (isset($_GET['order_sort']) && trim($_GET['order_sort'])) ? trim($_GET['order_sort']) : '';
		//积分商城商品
		$integral = (isset($_GET['integral']) && intval($_GET['integral'])) ? intval($_GET['integral']) : 0;
		//抢购
		$purchase = (isset($_GET['purchase']) && intval($_GET['purchase'])) ? intval($_GET['purchase']) : 0;
		if ($category_id) {
			$ids = $this->goods_mod->get_category_children_tree($category_id);
			$where .= " AND g.category_id IN ({$ids})";
		}
		if ($ext_property) {
			$exts = explode(',',$ext_property);
			$w = "";
			foreach ($exts as $e) {
				$w .= " OR CONCAT(',',g.ext_property,',') LIKE '%,{$e},%'";
			}
			$where .= " AND (".trim($w,' OR ').")";
		}
		if ($shop_id) {
			$where .= " AND g.shop_id='{$shop_id}'";
		}
		if ($country_id) {
			$where .= " AND g.country_id='{$country_id}'";
		}
		if ($brand_id) {
			$where .= " AND g.brand_id='{$brand_id}'";
		}
		if ($keyword) {
			//插入搜索记录表
			if ($this->member_id) {
				$sql = "DELETE FROM {$this->tbp}seach_history WHERE member_id='{$this->member_id}' AND content='{$keyword}'";
				$this->db->query($sql);
				$sql = "INSERT INTO {$this->tbp}seach_history (member_id, content, add_time) VALUES ('{$this->member_id}', '{$keyword}', '".time()."')";
				$this->db->query($sql);
			}
			$where .= " AND (g.name like '%{$keyword}%' OR g.description like '%{$keyword}%' OR g.keywords like '%{$keyword}%')";
		}
		if ($min_price) {
			$where .= " AND g.price>='{$min_price}'";
		}
		if ($max_price) {
			$where .= " AND g.price<='{$max_price}'";
		}
		if ($purchase) {
			$where .= " AND g.purchase_count>0 AND g.purchase_count>g.purchased";
		}
		if (!$order_sort) $order_sort = 'DESC';
		if ($order_sort =='DESC') $order_sort='ASC';
		switch ($order_field) {
			case 'id':
				$orderby = "g.id {$order_sort}";
				break;
			case 'sales':
				$orderby = "g.sales {$order_sort}";
				break;
			case 'price':
				$orderby = "g.price {$order_sort}";
				break;
			default:
				$orderby = "g.sort ASC, g.id DESC";
				break;
		}
		if ($integral) {
			$where .= " AND g.integral>0";
		}
		//20160105 by ajsong 商品表所有数据都返回
		$sql = "SELECT g.*
			FROM {$this->tbp}goods g
			WHERE g.status='1' {$where} ORDER BY {$orderby}
			LIMIT {$offset}, {$pagesize}";
		//echo $sql;exit;
		$goods = $this->db->get_results($sql);
		if ($goods) {
			foreach ($goods as $k => $g) {
				unset($goods[$k]->content);
				$goods[$k]->price = $this->goods_mod->get_min_price(array($g->price, $g->promote_price));
			}
			$goods = add_domain_deep($goods, array("pic"));
		}
		$flashes = $category = $categories = $brand = $brands = $country = $country_categories = NULL;
		//幻灯广告
		$flashes = $this->_flashes();
		//国家馆进入
		if ($country_id) {
			$sql = "SELECT * FROM {$this->tbp}country WHERE id='{$country_id}'";
			$country = $this->db->get_row($sql);
			$sql = "SELECT * FROM {$this->tbp}goods_category WHERE id IN 
				(SELECT distinct category_id FROM {$this->tbp}goods WHERE country_id='{$country_id}')";
			$country_categories = $this->db->get_results($sql);
		}
		//获取分类
		if ($category_id) {
			$sql = "SELECT * FROM {$this->tbp}goods_category WHERE id='{$category_id}'";
			$category = $this->db->get_row($sql);
			$categories = $this->goods_mod->get_categorys($category_id);
		}
		//获取品牌
		if ($brand_id) {
			$sql = "SELECT * FROM {$this->tbp}brand WHERE id='{$brand_id}'";
			$brand = $this->db->get_row($sql);
			$sql = "SELECT id, name FROM {$this->tbp}brand WHERE status='1' ORDER BY sort ASC, id DESC";
			$brands = $this->db->get_results($sql);
		}
		success(array("flashes"=>$flashes, "category"=>$category, "categories"=>$categories, "brand"=>$brand, "brands"=>$brands, "goods"=>$goods,
			"country"=>$country, "country_categories"=>$country_categories));
	}

	//幻灯广告
	private function _flashes() {
		$now = time();
		$sql = "SELECT * FROM {$this->tbp}ad WHERE position='integral' AND status='1'
			ORDER BY sort ASC, id DESC LIMIT 5";
		$ads = $this->db->get_results($sql);
		if ($ads) {
			$ads = add_domain_deep($ads, array("pic"));
		}
		return $ads;
	}

	//商品详情
	//用户扫描代理商的线下商品
	//http://domain/wap.php?app=goods&act=scan&qrcode=xxxxx
	public function scan() {
		$reseller_id = 0;
		$qrcode = (isset($_GET['qrcode']) && trim($_GET['qrcode'])) ? $_GET['qrcode'] : '';
		if ($qrcode) {
			$sql = "SELECT * FROM yd_order_goods WHERE qrcode='{$qrcode}'";
			$row = $this->db->get_row($sql);
			if ($row) {
				$reseller_id = $this->db->get_var("SELECT shop_id FROM yd_order WHERE id='{$row->order_id}'");
				if ($reseller_id) {
					header("Location:/wap.php?app=goods&act=detail&goods_id={$row->goods_id}&reseller={$reseller_id}");
					exit;
				} else {
					error("找不到对应的渠道商");
				}
			} else {
				error("找不到对应的条码");
				/*
				//根据防伪码获取商品id
				$sql = "SELECT goods_id FROM yd_test_qrcode WHERE qrcode='{$qrcode}'";
				$goods_id = intval($this->db->get_var($sql));
				if ($goods_id) {
					header("Location:/wap.php?app=goods&act=detail&goods_id={$goods_id}");
					exit;
				} else {
					error("找不到对应的条码");
				}
				*/
			}
		}
		error("找不到对应的商品");
	}

	//商品详情
	//代理商在商品详情分享
	public function detail() {
		$id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		$qrcode = (isset($_GET['qrcode']) && intval($_GET['qrcode'])) ? intval($_GET['qrcode']) : 0;
		$goods = $this->goods_mod->detail($id, true);
		if (!$goods) error('该商品不存在或已下架', -99);
		$shop = NULL;
		if ($goods->shop_id) {
			$sql = "SELECT s.*, p.name as province_name, c.name as city_name, d.name as district_name FROM {$this->tbp}shop s
				LEFT JOIN {$this->tbp}province p ON province_id=s.province
				LEFT JOIN {$this->tbp}city c ON city_id=s.city
				LEFT JOIN {$this->tbp}district d ON district_id=s.district
				WHERE s.id='{$goods->shop_id}'";
			$shop = $this->db->get_row($sql);
			if ($shop) {
				$shop->province = $shop->province_name;
				$shop->city = $shop->city_name;
				$shop->district = $shop->district_name;
			}
		}
		$goods->shop = $shop;
		if ($this->member_id) {
			$sql = "DELETE FROM {$this->tbp}member_goods_history WHERE member_id='{$this->member_id}' AND goods_id='{$id}'";
			$this->db->query($sql);
			$sql = "INSERT INTO {$this->tbp}member_goods_history (member_id, goods_id) VALUES ('{$this->member_id}', '{$id}')";
			$this->db->query($sql);
		}
		$sql = "UPDATE {$this->tbp}goods SET clicks=clicks+1 WHERE id='{$id}'";
		$this->db->query($sql);
		success($goods);
	}
	
	//获取最近店铺
	public function get_nearby_shop() {
		$latitude = (isset($_GET['latitude']) && floatval($_GET['latitude'])) ? floatval($_GET['latitude']) : 0;
		$longitude = (isset($_GET['longitude']) && floatval($_GET['longitude'])) ? floatval($_GET['longitude']) : 0;
		$sql = "SELECT *, fun_distance(latitude, longitude, {$latitude}, {$longitude}) as distance 
			FROM {$this->tbp}shop WHERE status=1 AND latitude>0 AND longitude>0 ORDER BY distance ASC LIMIT 1";
		$rs = $this->db->get_row($sql);
		if ($rs) {
			$_SESSION['reseller_id'] = $rs->member_id;
		}
		success($rs);
	}

	//检查防伪码是否有效
	public function check_qrcode() {
		$return = array("valid"=>"0", "shop"=>"0");
		$qrcode = (isset($_GET['qrcode']) && trim($_GET['qrcode'])) ? trim($_GET['qrcode']) : '';
		if ($qrcode) {
			$sql = "SELECT count(*) FROM yd_order_goods WHERE qrcode='{$qrcode}'";
			$exists = intval($this->db->get_var($sql));
			if ($exists) {
				error('防伪码已经被使用');
			}
			$qrcode = base64_encode($qrcode);
			$url = "{$this->domain}/api.php?app=goods&act=_check_qrcode&qrcode={$qrcode}";
			$json = file_get_contents($url);
			$json = json_decode($json);
			$return = $json;
		}
		success($return);
	}

	public function _check_qrcode() {
		$return = array("valid"=>"0", "shop"=>"0");
		$qrcode = (isset($_GET['qrcode']) && trim($_GET['qrcode'])) ? $_GET['qrcode'] : '';
		$qrcode = base64_decode($qrcode);
		$sql = "SELECT * FROM yd_test_qrcode WHERE qrcode='{$qrcode}'";
		$row = $this->db->get_row($sql);
		if ($row) {
			$return['valid'] = "1";
			$return['shop'] = $row->shop_id;
		}
		exit(json_encode($return));
	}

	public function create() {
		$this->create_edit();
	}

	public function edit() {
		$this->create_edit();
	}

	//发布、编辑商品
	public function create_edit() {
		file_put_contents(ROOT_PATH."/temp/upload.log", "======== begin ".date("Y-m-d H:i:s")." ===<br>  ", FILE_APPEND);
		$pic1 = "";
		$pics = array();
		$pic_memos = array();
		$goods_id = (isset($_POST['goods_id']) && intval($_POST['goods_id'])) ? intval($_POST['goods_id']) : 0;
		$name = (isset($_POST['name']) && trim($_POST['name'])) ? trim($_POST['name']) : '';
		$description = isset($_POST['description']) ? $_POST['description'] : '';
		//$specs = (isset($_POST['specs']) && trim($_POST['specs'])) ? trim($_POST['specs']) : '';
		//浏览权限
		$group_ids = (isset($_POST['group_ids']) && trim($_POST['group_ids'])) ? trim($_POST['group_ids']) : '';
		//规格
		$specs_string = (isset($_POST['specs']) && trim($_POST['specs'])) ? stripslashes($_POST['specs']) : '';
		//运费
		$shipping_fee = (isset($_POST['shipping_fee']) && floatval($_POST['shipping_fee'])) ? floatval($_POST['shipping_fee']) : 0;
		//分类
		$type_id = (isset($_POST['type_id']) && intval($_POST['type_id'])) ? intval($_POST['type_id']) : 0;
		//分利模板
		$commission_template_id = (isset($_POST['commission_template_id']) && floatval($_POST['commission_template_id'])) ? floatval($_POST['commission_template_id']) : 0;

		if ($name=='') {
			error("缺少商品资料");
		}
		//规格
		//规格名称1:价格1:促销价1:库存1
		$stocks = 0;
		if (!$specs_string) {
			//print_r($_SERVER);
			//print_r($_SESSION);
			error('请设置规格、价格、库存');
		}
		$specs = json_decode($specs_string);
		if (!$specs) error('请设置规格、价格、库存');
		$specs = $specs->specs;
		foreach ($specs as $key => $spec) {
			$stocks += $spec->stocks;
		}
		/*
		$specs_arr = explode("||", $specs_string);
		$specs = array();
		$stocks = 0;
		foreach ($specs_arr as $k => $str) {
			$arr = explode(":", $str);
			if (count($arr)==4) {
				$specs[] = $arr;
				$stocks += $arr[3];
			}
		}
		if (!$specs) {
			error('请设定商品规格');
		}
		*/
		//分利
		$commission1 = $commission2 = $commission3 = 0;
		if ($commission_template_id) {
			$sql = "SELECT * FROM yd_commission_template WHERE id='{$commission_template_id}' AND member_id='{$this->member_id}'";
			$commission_template = $this->db->get_row($sql);
			if ($commission_template) {
				$commission1 = $commission_template->commission1;
				$commission2 = $commission_template->commission2;
				$commission3 = $commission_template->commission3;
			} else {
				$commission1 = $commission2 = $commission3 = 0;
			}
		}
		//图片，最多9张
		for($i=1; $i<=9; $i++) {
			$pic = upload_one_file('goods', "pic{$i}");
			if ($pic) $pics[] = $pic;
			file_put_contents(ROOT_PATH."/temp/upload.log", date("Y-m-d H:i:s")."\\r\\n", FILE_APPEND);
			$pic_memos[] = (isset($_POST["memo{$i}"]) && trim($_POST["memo{$i}"])) ? trim($_POST["memo{$i}"]) : '';
		}
		if (count($pics)==0) {
			error("至少需要一张商品图片");
		}
		if ($goods_id) {
			//只能编辑我的商品
			$sql = "SELECT count(*) FROM yd_goods WHERE id='{$goods_id}' AND shop_id='{$this->shop_id}'";
			if (!intval($this->db->get_var($sql))) error('您没有编辑该商品的权限');
			$sql = "UPDATE yd_goods SET name='{$name}', pic='".$pics[0]."', price='".$specs[0]->price."',
				special_price='".$specs[0]->special_price."', stocks='{$stocks}', type_id='{$type_id}', edit_time='".time()."',
				description='{$description}', shipping_fee='{$shipping_fee}', commission_template_id='{$commission_template_id}',
				commission1='{$commission1}', commission2='{$commission2}', commission3='{$commission3}'
				WHERE id='{$goods_id}' AND shop_id='{$this->shop_id}'";
			$this->db->query($sql);
		} else {
			//写入数据
			$sql = "INSERT INTO yd_goods(name, pic, price, special_price, stocks, sales, clicks, comments, type_id,
				add_time, status, sort, description, shop_id, shipping_fee, commission_template_id,
				commission1, commission2, commission3)
				VALUES('{$name}', '".$pics[0]."', '".$specs[0]->price."', '".$specs[0]->special_price."','{$stocks}', '0', '0', '0', '{$type_id}',
				'".time()."', '1', '999', '{$description}', '{$this->shop_id}', '{$shipping_fee}', '{$commission_template_id}',
				'{$commission1}', '{$commission2}', '{$commission3}'
			)";
			//echo $sql;
			$this->db->query($sql);
			$goods_id = $this->db->insert_id;
		}

		file_put_contents(ROOT_PATH."/temp/upload.log", date("Y-m-d H:i:s")."\\r\\n", FILE_APPEND);
		if ($goods_id) {
			//写入权限
			//$this->goods_mod->add_own_privilege($goods_id);
			//写入规格
			if ($specs) {
				$sql = "DELETE FROM yd_goods_spec WHERE goods_id='{$goods_id}'";
				$this->db->query($sql);
				foreach ($specs as $spec) {
					//$sql = "INSERT INTO yd_goods_spec(spec, price, special_price, stocks, goods_id)
					//	VALUES('".$spec[0]."', '".$spec[1]."', '".$spec[2]."', '".$spec[3]."', '{$goods_id}')";
					$sql = "INSERT INTO yd_goods_spec(spec, price, special_price, stocks, goods_id)
						VALUES('{$spec->spec}', '{$spec->price}', '{$spec->special_price}', '{$spec->stocks}', '{$goods_id}')";
					$this->db->query($sql);
				}
			}
			//写入图片
			if ($pics) {
				$sql = "DELETE FROM yd_goods_pic WHERE goods_id='{$goods_id}'";
				$this->db->query($sql);
				for ($i=0; $i<count($pics); $i++) {
					$pic = $pics[$i];
					$memo = $pic_memos[$i];
					if ($pic) {
						$sql = "INSERT INTO yd_goods_pic(goods_id, shop_id, pic, memo, add_time)
							VALUES('{$goods_id}', '{$this->shop_id}', '{$pic}', '{$memo}', '".time()."')";
						$this->db->query($sql);
					}
				}
			}
			//更新商品数
			$sql = "UPDATE yd_shop SET goods=(SELECT COUNT(*) FROM yd_goods WHERE shop_id='{$this->shop_id}') WHERE id='{$this->shop_id}'";
			$this->db->query($sql);
			file_put_contents(ROOT_PATH."/temp/upload.log", "======== end ".date("Y-m-d H:i:s")." ===<br>  ", FILE_APPEND);
			success($goods_id);
		}
		error("发布商品失败");
	}

	//上架商品
	public function on_sale() {
		$goods_id = (isset($_POST['goods_id']) && trim($_POST['goods_id'])) ? intval($_POST['goods_id']) : 0;
		$stocks = (isset($_POST['stocks']) && trim($_POST['stocks'])) ? intval($_POST['stocks']) : 0;
		if ($goods_id) {
			//重新上架，需要将商品显示在前面 by willson 2015/9/25
			//添加时间，也设置成重新上架时间
			$field = '';
			if ($stocks) $field = ", stocks='{$stocks}'";
			$sql = "UPDATE yd_goods SET status=1, edit_time='".time()."' {$field} WHERE id='{$goods_id}' AND shop_id='{$this->shop_id}'";
			$this->db->query($sql);
			//店铺的商品数量增加1
			$this->_recaculate_goods();
		}
		success("ok");
	}

	//下架商品
	public function off_sale() {
		$goods_id = (isset($_POST['goods_id']) && trim($_POST['goods_id'])) ? intval($_POST['goods_id']) : 0;
		if ($goods_id) {
			$sql = "UPDATE yd_goods SET status=0 WHERE id='{$goods_id}' AND shop_id='{$this->shop_id}'";
			$this->db->query($sql);
			//店铺的商品数量增加1
			//$sql = "UPDATE yd_shop SET goods=goods+1 WHERE id='{$this->shop_id}' AND member_id='{$this->member_id}'";
			//重新计算店铺商品数量
			$this->_recaculate_goods();
		}
		success("ok");
	}

	//删除商品
	public function delete() {
		$goods_id = (isset($_POST['goods_id']) && trim($_POST['goods_id'])) ? intval($_POST['goods_id']) : 0;
		if ($goods_id) {
			$sql = "DELETE FROM yd_goods WHERE id='{$goods_id}' AND shop_id='{$this->shop_id}'";
			$this->db->query($sql);
			//删除规格
			//删除图片
			//店铺的商品数量增加1
			//$sql = "UPDATE yd_shop SET goods=goods+1 WHERE id='{$this->shop_id}' AND member_id='{$this->member_id}'";
			//重新计算店铺商品数量
			$this->_recaculate_goods();
		}
		success("ok");
	}

	private function _recaculate_goods() {
		$sql = "UPDATE yd_shop SET goods=(SELECT COUNT(*) FROM yd_goods WHERE shop_id='{$this->shop_id}') WHERE id='{$this->shop_id}'";
		$this->db->query($sql);
	}
	
	public function video() {
		$path = (isset($_GET['path']) && trim($_GET['path'])) ? trim($_GET['path']) : '';
		$html = '<!doctype html>
		<html>
		<head>
		<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,initial-scale=1.0,user-scalable=0" />
		<meta name="format-detection" content="telephone=no" />
		<meta name="format-detection" content="email=no" />
		<meta name="format-detection" content="address=no" />
		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta charset="UTF-8">
		<title>视频播放</title>
		<style>
		html, body{background:#000; height:100%; margin:0; padding:0; overflow:hidden;}
		</style>
		</head>
		<body>
		<video width="100%" height="100%" poster="" preload="auto" autoplay controls>
		<source src="'.$path.'" type="video/mp4" />
		您的浏览器不支持 video 标签。
		</video>
		</body>
		</html>';
		echo $html;
		exit;
	}
}
